package simple;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;

import org.junit.Test;

import com.simple.bsp.common.util.HttpUtil;
import com.simple.video.Patterns;

public class Douyin {
	
	
	@Test
	public void testDouyin() throws Exception{

		String url ="我是中国人https://v.douyin.com/vdjh8X 哈哈哈哈";
		 Matcher matcher = Patterns.WEB_URL.matcher(url);
		 if (matcher.find()){
		        System.out.println(matcher.group());
		        url = matcher.group();
		}
		String content = HttpUtil.get(url,"1");
		
		String tt = content.split("playAddr:")[1];
		String bb = tt.split("cover")[0].replace("\"", "").replace(",","");
		System.out.println(bb);
		String realPath = bb.replace("playwm", "play");
		System.out.println(realPath);
		String content2 = getHeader(realPath,"0");		
		System.out.println(content2);
		
	}
	
	
	public static String getHeader(String urlStr ,String isPc) throws Exception{
        HttpURLConnection conn = null;
        try{
            //创建URL对象
            URL url = new URL(urlStr);
            //获取URL连接
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Accept-Language", "zh-CN");
            if("1".equals(isPc)){
            	conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
            }else{
            	conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");
            }
            
            conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
            //建立实际的连接
            conn.connect();
            //获取响应的内容
            return conn.getHeaderField("Location");
        }finally{
            if(null!=conn) conn.disconnect();
        }
    }
	
	   
	   /**
	     * 读取响应字节流并将之转为字符串
	     * @param in
	     *         要读取的字节流
	     * @return
	     * @throws IOException
	     */
	    private static String readResponseContent(InputStream in) throws IOException{
	        Reader reader = null;
	        StringBuilder content = new StringBuilder();
	        try{
	            reader = new InputStreamReader(in);
	            char[] buffer = new char[1024];
	            int head = 0;
	            while( (head=reader.read(buffer))>0 ){
	                content.append(new String(buffer, 0, head));
	            }
	            return content.toString();
	        }finally{
	            if(null!=in) in.close();
	            if(null!=reader) reader.close();
	        }
	    }
	

}
